import React, { useState, useEffect } from "react";
import { DatePicker, Radio, Space, Button, Card, message } from "antd";
import moment, { Moment } from "moment";
import "./TimeRangeSelector.css";

const { RangePicker } = DatePicker;

interface TimeRangeSelectorProps {
  initialRange?: {label?:string, value:[Moment | null, Moment | null] };
  style?: React.CSSProperties;
  onChanged?: (range: { start: Date; end: Date }) => void;
}

type QuickOption = {
  label: string;
  value: string;
};

const quickOptions: QuickOption[] = [
  { label: "近5分钟", value: "5m" },
  { label: "近15分钟", value: "15m" },
  { label: "近30分钟", value: "30m" },
  { label: "近1小时", value: "1h" },
  { label: "近3小时", value: "3h" },
  { label: "近6小时", value: "6h" },
  { label: "近12小时", value: "12h" },
  { label: "近24小时", value: "24h" },
  { label: "今天", value: "today" },
  { label: "昨天", value: "yesterday" },
  { label: "本周", value: "thisWeek" },
  { label: "上周", value: "lastWeek" },
  { label: "本月", value: "thisMonth" },
  { label: "上月", value: "lastMonth" },
  { label: "自定义", value: "custom" },
];

const calculateTimeRange = (option: string): [Moment, Moment] => {
  const now = moment();
  switch (option) {
    case "5m": return [now.clone().subtract(5, "minutes"), now];
    case "15m": return [now.clone().subtract(15, "minutes"), now];
    case "30m": return [now.clone().subtract(30, "minutes"), now];
    case "1h": return [now.clone().subtract(1, "hour"), now];
    case "3h": return [now.clone().subtract(3, "hours"), now];
    case "6h": return [now.clone().subtract(6, "hours"), now];
    case "12h": return [now.clone().subtract(12, "hours"), now];
    case "24h": return [now.clone().subtract(24, "hours"), now];
    case "today": return [now.clone().startOf("day"), now];
    case "yesterday": return [
      now.clone().subtract(1, "day").startOf("day"),
      now.clone().subtract(1, "day").endOf("day"),
    ];
    case "thisWeek": return [now.clone().startOf("week"), now];
    case "lastWeek": return [
      now.clone().subtract(1, "week").startOf("week"),
      now.clone().subtract(1, "week").endOf("week"),
    ];
    case "thisMonth": return [now.clone().startOf("month"), now];
    case "lastMonth": return [
      now.clone().subtract(1, "month").startOf("month"),
      now.clone().subtract(1, "month").endOf("month"),
    ];
    default: return [now, now];
  }
};

const TimeRangeSelector: React.FC<TimeRangeSelectorProps> = ({
  initialRange,
  style,
  onChanged,
}) => {
  const [timeRange, setTimeRange] = useState<[Moment | null, Moment | null]>([null, null]);
  const [selectedOption, setSelectedOption] = useState<string>("5m");
  const [customSelected, setCustomSelected] = useState<boolean>(false);
  // const [defaultQuickSelected, setDefaultQuickSelected] = useState<string>('30m');

  useEffect(() => {
    if (initialRange && initialRange.value[0] && initialRange.value[1]) {
      setTimeRange(initialRange.value);
      if (initialRange.label){
        const value = findValueByLabel(initialRange.label);
        if (value !==undefined){
          // console.info("init defaultQuickSelect:"+value)
          setSelectedOption(value);
        }
      }
      // setSelectedOption("custom");
      setCustomSelected(true);
    }
  }, [initialRange]);

  const findValueByLabel = (label: string): string | undefined => {
    const option = quickOptions.find(opt => opt.label === label);
    return option?.value;
  };

  const findLabelByValue = (value: string): string | undefined => {
    const option = quickOptions.find(opt => opt.value === value);
    return option?.label;
  };

  const handleQuickOptionSelect = (e: any) => {
    const option = e.target.value;
    const optionLabel = findLabelByValue(option)
    setSelectedOption(option);
    setCustomSelected(option === "custom");

    if (option !== "custom") {
      const range = calculateTimeRange(option);
      setTimeRange(range);
      onChanged?.({
        label: optionLabel,
        start: range[0].toDate(),
        end: range[1].toDate(),
      });
    }
  };

  const handleRangeChange = (dates: [Moment | null, Moment | null] | null) => {
    if (dates) {
      setTimeRange(dates);
      setSelectedOption("custom");
      setCustomSelected(true);
    }
  };

  const applyTimeRange = () => {
    if (timeRange[0] && timeRange[1]) {
      onChanged?.({
        start: timeRange[0].toDate(),
        end: timeRange[1].toDate(),
      });
    } else {
      message.error("请选择有效的时间范围");
    }
  };

  const containerStyle = {
    width: "100%",
    maxWidth: "550px",
    margin: "0 auto",
    ...style,
  };

  

  return (
    <Card style={{ maxWidth: 500 }}>
      <div style={{ display: "flex", gap: 15 }}>
        {/* 左侧：绝对时间选择器 */}
        <div style={{ flex: 1 }}>
          <RangePicker
            showTime={{ format: "HH:mm", minuteStep: 5 }}
            format="YYYY-MM-DD HH:mm"
            value={timeRange}
            onChange={handleRangeChange}
            style={{ width: "100%", marginBottom: 8 }}
            // disabled={!customSelected}
          />
          <Button
            type="primary"
            onClick={applyTimeRange}
            disabled={!timeRange[0] || !timeRange[1]}
            block
          >
            应用时间范围
          </Button>
        </div>

        {/* 右侧：快捷选择，滚动展示 */}
        <div
          style={{
            width: 120,
            maxHeight: 250,
            overflowY: "auto",
            scrollbarWidth: "thin", // 细滚动条
            scrollbarColor: "inherit", // 跟随系统颜色
          }}
        >
          <Radio.Group
            value={selectedOption}
            onChange={handleQuickOptionSelect}
            buttonStyle="solid"  
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 8,
              paddingRight: 4, // 为滚动条留出空间
            }}
          >
            {quickOptions.map((option) => (
              <Radio.Button
                key={option.value}
                value={option.value}
                style={{
                  width: "100%",
                  textAlign: "left",
                  padding: "4px 8px",
                }}
              >
                {option.label}
              </Radio.Button>
            ))}
          </Radio.Group>
        </div>
      </div>
    </Card>
  );
  
};

export default TimeRangeSelector;
